package cn.factorybox.auth.controller;

import cn.factorybox.auth.service.AuthService;
import cn.factorybox.client.UserClient;
import cn.factorybox.common.entity.Constant;
import cn.factorybox.common.entity.Result;
import cn.factorybox.common.utils.BeanMapUtils;
import cn.factorybox.common.utils.CookieUtils;
import cn.factorybox.config.JwtProperties;
import cn.factorybox.entity.UserInfo;
import cn.factorybox.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author flypig
 * @version 1.0
 * @date 2020-03-28 12:54
 */

@RestController
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserClient userClient;

    @PostMapping("accredit")
    @ResponseBody
    public Result accredit(
            @RequestParam(value = "username", required = false) String uName,
            @RequestParam(value = "password", required = false) String uPass,
            HttpServletRequest request,
            HttpServletResponse response) {

        String token = this.authService.accredit(uName,uPass);

        if (StringUtils.isBlank(token)) {
            log.error("{}用户登录失败，验证失败",uName);
            return Result.error(Constant.SUCCEED_CODE,"验证失败");
        }
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        Map<String,Object> map = new HashMap<>();
        map.put("data",tokenMap);
        log.info("{}用户登录成功，获取token",uName);
        return Result.ok(map,"登录成功，获取token");
    }

    /**
     * 认证
     * @param request
     * @param response
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<Map<String,Object>> verify(
            HttpServletRequest request,
            HttpServletResponse response) {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            Map<String,Object> map = new HashMap<>();
            map.put("code", Constant.ERROR_CODE);
            map.put("msg","缺少必要认证信息");
            log.error("用户认证失败，缺少必要认证信息token");
            return  ResponseEntity.ok(map);
        }
        try {
            // 通过jwt工具类使用公钥解析jwt
            UserInfo userInfo = JwtUtils.getInfoFromToken(token,this.jwtProperties.getKey());
            if (!JwtUtils.checkObjFieldIsNotNull(userInfo)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            // 刷新jwt中的有效时间
            token =  JwtUtils.generateToken(userInfo,this.jwtProperties.getKey(),this.jwtProperties.getExpire());

            // 刷新cookie中的有效时间, 指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire()*60,null,true);

            Map<String,Object> result = BeanMapUtils.beanToMap(userInfo);
            Map<String,Object> maps = new HashMap<>();
            maps.put("code",Constant.SUCCEED_CODE);
            maps.put("flag",true);
            maps.put("message","成功获取用户信息");
            maps.put("data",result);
            log.info("{}用户认证成功，成功获取用户信息",userInfo.getUsername());
            return ResponseEntity.ok(maps);
        } catch (Exception e) {
            log.error("用户认证抛出异常Exception：{}",e);
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    @GetMapping("logout")
    public Result logout() {
        log.info("用户成功退出后台系统");
        return Result.ok("成功退出");
    }

}
